/*
 * @Author: liuxiao
 * @Date: 2023-11-25 00:55:46
 * @Last Modified by: liuxiao
 * @Last Modified time: 2023-11-29 01:32:28
 * @控制器层：处理路由对应的方法
 */
//导入bcrypt
const bcrypt = require('bcryptjs')

const jwt = require('jsonwebtoken')

const {
  createUser,
  getUserInfo,
  updateById
} = require('../service/user.service')
const {
  userRegisterError,
  samePassword,
  changePassword
} = require('../constant/err.type')

class UserController {
  //注册用户方法
  async register(ctx, next) {
    //1.获取数据
    const { username, password } = ctx.request.body

    //2.操作数据库
    try {
      const res = await createUser(username, password)
      // console.log(res)

      //3.返回结果
      ctx.body = {
        code: 0,
        message: '用户注册成功',
        data: {
          id: res.id,
          username: res.username
        }
      }
    } catch (err) {
      ctx.app.emit('error', userRegisterError, ctx)
    }
  }

  //登录方法
  async login(ctx, next) {
    const { username } = ctx.request.body

    //1.获取用户信息
    try {
      const result = await getUserInfo({ username })
      //从返回结果对象中剔除password属性，将剩下的属性放到新的对象中
      const { password, ...res } = result

      const { JWT_SECRET } = process.env

      ctx.body = {
        code: 0,
        message: '用户登录成功',
        data: {
          token: jwt.sign(res, JWT_SECRET, { expiresIn: '1d' })
        }
      }
    } catch (err) {
      console.error('用户登录失败！', err) //写入日志
      //ctx.app.emit('error', userRegisterError, ctx)
      //不要忘记写return
      return
    }
  }

  //修改密码方法
  async changePassword(ctx, next) {
    //1.获取数据
    //id为state的数据，因为在解析token时，user数据被写在ctx.state中
    const id = ctx.state.user.id
    //newpassword为
    const newPassword = ctx.request.body.new_password
    const username = ctx.state.user.username
    console.log(newPassword);

    try {
      const res = await getUserInfo({ username })
      if (bcrypt.compareSync(newPassword, res.password)) {
        ctx.app.emit('error', samePassword, ctx)
        return
      }

      //加盐
      const salt = bcrypt.genSaltSync(10)
      //hash保存的是密文
      const hash = bcrypt.hashSync(newPassword, salt)
      const password = hash

      //2.操作数据库
      if (await updateById({ id, password })) {
        ctx.body = {
          code: 0,
          message: '修改密码成功！',
          data: ''
        }
      }
    } catch (err) {
      console.log('修改密码失败')
      ctx.app.emit('error', changePassword, ctx)
    }
  }
}

module.exports = new UserController()
